package com.ttdevs.socket.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;

import com.ttdevs.socket.ISocket;
import com.ttdevs.socket.util.BaseThread;
import com.ttdevs.socket.util.SocketConfig;

public class TCPReceiver extends BaseThread {

	private ISocket mSocket;
	private InputStream is;
	private byte[] receiveBuffer;
	private BlockingQueue<byte[]> mReceiverQueue;

	public TCPReceiver(BlockingQueue<byte[]> receiverQueue, ISocket socket, InputStream is) {
		mSocket = socket;
		mReceiverQueue = receiverQueue;
		this.is = is;
	}

	@Override
	public boolean prepare() {
		if (mSocket == null || mReceiverQueue == null || is == null) {
			return false;
		}
		receiveBuffer = new byte[SocketConfig.RECEIVERBUFFERSIZE];
		return super.prepare();
	}

	@Override
	public void execute() {
		try {
			int count = is.read(receiveBuffer);
			if (count == -1) {
				notifyError();
			}
			byte[] data = getPacket(receiveBuffer, count, is);
			mReceiverQueue.put(data);
		} catch (InterruptedException e) {
			e.printStackTrace();
			notifyError();
		} catch (IOException e) {
			e.printStackTrace();
			notifyError();
		}
	}

	private byte[] getPacket(byte[] buffer, int count, InputStream is) throws IOException {
		byte[] data = new byte[count];
		System.arraycopy(buffer, 0, data, 0, count);
		// TODO

		// while (contentLen < IMsgCmd.LEN_MSG_HEAD) {
		// readLen = is.read(msgHead, contentLen, msgHead.length - contentLen);
		// if (readLen < 0) {
		// throw new IOException("readLen == -1");
		// }
		//
		// contentLen += readLen;
		// }
		//
		// if (msgHead[IMsgCmd.INDEX_SYNC_TAG] != IMsgCmd.SYNC_TAG_B[0] ||
		// msgHead[IMsgCmd.INDEX_SYNC_TAG + 1] != IMsgCmd.SYNC_TAG_B[1]) {
		// throw new IOException("head not is 0xaa55");
		// }
		//
		// int msgContentLen = ByteUtil.twoBytesToInt_2(msgHead);
		// if (msgContentLen < IMsgCmd.LEN_MSG_HEAD) {
		// throw new IOException("length < IMsgCmd.LEN_MSG_HEAD");
		// }
		// byte[] msg = new byte[msgContentLen];
		//
		// contentLen = IMsgCmd.LEN_MSG_HEAD;
		// while (contentLen < msg.length) {
		// readLen = is.read(msg, contentLen, msg.length - contentLen);
		// if (readLen < 0) {
		// throw new IOException("readLen == -1");
		// }
		//
		// contentLen += readLen;
		// }
		//
		// System.arraycopy(msgHead, 0, msg, 0, msgHead.length);

		return data;
	}

	private void notifyError() {
		mSocket.close(true, true);
		this.quit();
	}
}
